package com.ruoyi.project.ledger.service.impl;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExportUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.ledger.domain.LedgerFile;
import com.ruoyi.project.ledger.domain.LedgerSafetyManagementInspectionDaily;
import com.ruoyi.project.ledger.mapper.LedgerFileMapper;
import com.ruoyi.project.ledger.mapper.LedgerSafetyManagementInspectionDailyMapper;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import org.apache.poi.ss.usermodel.Workbook;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.ledger.mapper.LedgerSafetyManagementInspectionMapper;
import com.ruoyi.project.ledger.domain.LedgerSafetyManagementInspection;
import com.ruoyi.project.ledger.service.ILedgerSafetyManagementInspectionService;

/**
 * 安全管理监督检查台账Service业务层处理
 *
 * @author gwc
 * @date 2020-04-14
 */
@Service
public class LedgerSafetyManagementInspectionServiceImpl implements ILedgerSafetyManagementInspectionService
{
    @Autowired
    private LedgerSafetyManagementInspectionMapper ledgerSafetyManagementInspectionMapper;
    @Autowired
    private LedgerFileMapper ledgerFileMapper;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private LedgerSafetyManagementInspectionDailyMapper dailyMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 查询安全管理监督检查台账
     *
     * @param id 安全管理监督检查台账ID
     * @return 安全管理监督检查台账
     */
    @Override
    public LedgerSafetyManagementInspection selectLedgerSafetyManagementInspectionById(Long id)
    {
        LedgerSafetyManagementInspection inspection = ledgerSafetyManagementInspectionMapper.selectLedgerSafetyManagementInspectionById(id);
        if(inspection != null){
            if ("0".equals(inspection.getCheckType()) && inspection.getIsBefore().equals("0")){
                List<LedgerSafetyManagementInspectionDaily> dailies = dailyMapper.selectLedgerSafetyManagementInspectionDailyList(new LedgerSafetyManagementInspectionDaily(id));
                dailies.forEach(dailiy ->{
                    LedgerFile ledgerFile = new LedgerFile();
                    ledgerFile.setLedgerId(dailiy.getId());
                    ledgerFile.setLedgerType("11");      // 日常检查
                    // 检查
                    ledgerFile.setFileName("1");
                    List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList2(ledgerFile);
                    dailiy.setImgList(imgList);
                    // 整改
                    ledgerFile.setFileName("2");
                    List<Map<String, Object>> checkImgsList = ledgerFileMapper.selectLedgerImgList2(ledgerFile);
                    dailiy.setCheckImgsList(checkImgsList);
                });
                inspection.setDailies(dailies);
            }else {
                // 获取图片
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerId(id);
                ledgerFile.setLedgerType("5");      // 安全管理监督检查记录
                // 检查
                ledgerFile.setFileName("1");
                List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList2(ledgerFile);
                inspection.setImgList(imgList);
                // 检查
                ledgerFile.setFileName("2");
                List<Map<String, Object>> checkImgsList = ledgerFileMapper.selectLedgerImgList2(ledgerFile);
                inspection.setCheckImgsList(checkImgsList);
            }
        }
        return inspection;
    }

    /**
     * 查询安全管理监督检查台账列表
     *
     * @param ledgerSafetyManagementInspection 安全管理监督检查台账
     * @return 安全管理监督检查台账
     */
    @Override
    public List<LedgerSafetyManagementInspection> selectLedgerSafetyManagementInspectionList(LedgerSafetyManagementInspection ledgerSafetyManagementInspection)
    {
        return ledgerSafetyManagementInspectionMapper.selectLedgerSafetyManagementInspectionList(ledgerSafetyManagementInspection);
    }

    /**
     * 新增安全管理监督检查台账
     *
     * @param ledgerSafetyManagementInspection 安全管理监督检查台账
     * @return 结果
     */
    @Override
    public int insertLedgerSafetyManagementInspection(LedgerSafetyManagementInspection ledgerSafetyManagementInspection)
    {
        boolean flag = false;
        boolean flag2 = false;
        ledgerSafetyManagementInspection.setCreateTime(DateUtils.getNowDate());
        int i = ledgerSafetyManagementInspectionMapper.insertLedgerSafetyManagementInspection(ledgerSafetyManagementInspection);
        if ("0".equals(ledgerSafetyManagementInspection.getCheckType())){  // 日常检查
           if (ledgerSafetyManagementInspection.getDailies()!= null && ledgerSafetyManagementInspection.getDailies().size() >0){
               for (LedgerSafetyManagementInspectionDaily daily : ledgerSafetyManagementInspection.getDailies()){
                   daily.setInspectionId(ledgerSafetyManagementInspection.getId());
                   daily.setCreateId(ledgerSafetyManagementInspection.getCreateId());
                   daily.setCreateTime(DateUtils.getNowDate());
                   if ("0".equals(daily.getRectificationType())){
                       daily.setIsRectification("1");
                   }
                   // 是否有问题
                   if ("1".equals(daily.getIsProblems())){
                       flag = true;
                   }
                   // 是否整改完成
                   if (!"0".equals(daily.getRectificationType())){
                       flag2 = true;
                   }
                   int j = dailyMapper.insertLedgerSafetyManagementInspectionDaily(daily);
                   if (daily.getImgs() != null && daily.getImgs().length >0){
                       for (String path : daily.getImgs()){
                           LedgerFile ledgerFile = new LedgerFile();
                           ledgerFile.setLedgerType("11");
                           ledgerFile.setLedgerId(daily.getId());
                           ledgerFile.setFilePath(path);
                           ledgerFile.setFileName("1");
                           ledgerFile.setCreateId(daily.getCreateId());
                           ledgerFile.setCreateTime(DateUtils.getNowDate());
                           ledgerFileMapper.insertLedgerFile(ledgerFile);
                       }
                   }
               };
           }
        }else {
            // 添加图片
            if(ledgerSafetyManagementInspection.getImgs() != null && ledgerSafetyManagementInspection.getImgs().length > 0){
                for(String path : ledgerSafetyManagementInspection.getImgs()){
                    LedgerFile ledgerFile = new LedgerFile();
                    ledgerFile.setLedgerType("5");    // 安全管理监督检查记录
                    ledgerFile.setLedgerId(ledgerSafetyManagementInspection.getId());
                    ledgerFile.setFilePath(path);
                    ledgerFile.setFileName("1"); // 检查图片
                    ledgerFile.setCreateId(ledgerSafetyManagementInspection.getCreateId());
                    ledgerFile.setCreateTime(DateUtils.getNowDate());
                    ledgerFileMapper.insertLedgerFile(ledgerFile);
                }
            }
        }
        if (flag){
            ledgerSafetyManagementInspection.setIsProblems("1");
            if (!flag2){
                ledgerSafetyManagementInspection.setIsRectification("1");
                ledgerSafetyManagementInspection.setIsUpdate("1");
            }
            ledgerSafetyManagementInspectionMapper.updateLedgerSafetyManagementInspection(ledgerSafetyManagementInspection);
        }
        return i;
    }

    /**
     * 修改安全管理监督检查台账
     *
     * @param ledgerSafetyManagementInspection 安全管理监督检查台账
     * @return 结果
     */
    @Override
    public int updateLedgerSafetyManagementInspection(LedgerSafetyManagementInspection ledgerSafetyManagementInspection)
    {
        ledgerSafetyManagementInspection.setUpdateTime(DateUtils.getNowDate());
        int i = ledgerSafetyManagementInspectionMapper.updateLedgerSafetyManagementInspection(ledgerSafetyManagementInspection);
        // 日常检查
        boolean flag = false;
        boolean flag2 = false;
        if ("0".equals(ledgerSafetyManagementInspection.getCheckType())){
            if (ledgerSafetyManagementInspection.getDailies() != null && ledgerSafetyManagementInspection.getDailies().size()>0){
                for (LedgerSafetyManagementInspectionDaily daily : ledgerSafetyManagementInspection.getDailies()){
                    if ("0".equals(daily.getRectificationType())){
                        daily.setIsRectification("1");
                    }else {
                        daily.setIsRectification("0");
                    }
                    int j = dailyMapper.updateLedgerSafetyManagementInspectionDaily(daily);
                    LedgerFile ledgerFile = new LedgerFile();
                    ledgerFile.setLedgerId(daily.getId());
                    ledgerFile.setLedgerType("11");
                    ledgerFileMapper.deleteLedgerImg(ledgerFile);
                    if (daily.getImgs() != null && daily.getImgs().length >0){
                        for (String path : daily.getImgs()){
                            ledgerFile = new LedgerFile();
                            ledgerFile.setLedgerType("11");    // 日常检查
                            ledgerFile.setLedgerId(daily.getId());
                            ledgerFile.setFilePath(path);
                            ledgerFile.setFileName("1"); // 检查图片
                            ledgerFile.setCreateId(daily.getCreateId());
                            ledgerFile.setCreateTime(DateUtils.getNowDate());
                            ledgerFileMapper.insertLedgerFile(ledgerFile);
                        }
                    }
                    if ("1".equals(daily.getIsProblems())){
                        flag = true;
                    }
                    if (!"0".equals(daily.getRectificationType())){
                        flag2 = true;
                    }
                }
            }
            if (flag){
                ledgerSafetyManagementInspection.setIsProblems("1");
                if (!flag2){
                    ledgerSafetyManagementInspection.setIsRectification("1");
                    ledgerSafetyManagementInspection.setIsUpdate("1");
                }
                ledgerSafetyManagementInspectionMapper.updateLedgerSafetyManagementInspection(ledgerSafetyManagementInspection);
            }else {
                ledgerSafetyManagementInspection.setIsProblems("0");
                ledgerSafetyManagementInspectionMapper.updateLedgerSafetyManagementInspection(ledgerSafetyManagementInspection);
            }
        }else {
            // 删除台账图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(ledgerSafetyManagementInspection.getId());
            ledgerFile.setLedgerType("5");      // 安全管理监督检查记录
            ledgerFileMapper.deleteLedgerImg(ledgerFile);
            if(ledgerSafetyManagementInspection.getImgs() != null && ledgerSafetyManagementInspection.getImgs().length > 0){
                for(String path : ledgerSafetyManagementInspection.getImgs()){
                    ledgerFile = new LedgerFile();
                    ledgerFile.setLedgerType("5");    // 安全管理监督检查记录
                    ledgerFile.setLedgerId(ledgerSafetyManagementInspection.getId());
                    ledgerFile.setFilePath(path);
                    ledgerFile.setFileName("1"); // 检查图片
                    ledgerFile.setCreateId(ledgerSafetyManagementInspection.getUpdateId());
                    ledgerFile.setCreateTime(DateUtils.getNowDate());
                    ledgerFileMapper.insertLedgerFile(ledgerFile);
                }
            }
            if(ledgerSafetyManagementInspection.getCheckImgs() != null && ledgerSafetyManagementInspection.getCheckImgs().length > 0){
                for(String path : ledgerSafetyManagementInspection.getCheckImgs()){
                    ledgerFile = new LedgerFile();
                    ledgerFile.setLedgerType("5");    // 安全管理监督检查记录
                    ledgerFile.setLedgerId(ledgerSafetyManagementInspection.getId());
                    ledgerFile.setFilePath(path);
                    ledgerFile.setFileName("2"); // 复查图片
                    ledgerFile.setCreateId(ledgerSafetyManagementInspection.getUpdateId());
                    ledgerFile.setCreateTime(DateUtils.getNowDate());
                    ledgerFileMapper.insertLedgerFile(ledgerFile);
                }
            }
        }
        return i;
    }

    /**
     * 批量删除安全管理监督检查台账
     *
     * @param ids 需要删除的安全管理监督检查台账ID
     * @return 结果
     */
    @Override
    public int deleteLedgerSafetyManagementInspectionByIds(Long[] ids)
    {
        int i = ledgerSafetyManagementInspectionMapper.deleteLedgerSafetyManagementInspectionByIds(ids);
        for(Long id : ids){
            // 删除台账图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(id);
            ledgerFile.setLedgerType("5");      // 安全管理监督检查记录
            ledgerFileMapper.deleteLedgerImg(ledgerFile);
        }
        return i;
    }

    /**
     * 删除安全管理监督检查台账信息
     *
     * @param id 安全管理监督检查台账ID
     * @return 结果
     */
    @Override
    public int deleteLedgerSafetyManagementInspectionById(Long id)
    {
        int i = ledgerSafetyManagementInspectionMapper.deleteLedgerSafetyManagementInspectionById(id);
        List<LedgerSafetyManagementInspectionDaily> dailies = dailyMapper.selectLedgerSafetyManagementInspectionDailyList(new LedgerSafetyManagementInspectionDaily(id));
        if (dailies != null && dailies.size() >0){
            for (LedgerSafetyManagementInspectionDaily  daily: dailies){
                dailyMapper.deleteLedgerSafetyManagementInspectionDailyById(daily.getId());
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerId(daily.getId());
                ledgerFile.setLedgerType("11");
                ledgerFileMapper.deleteLedgerImg(ledgerFile);
            }
        }
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(id);
        ledgerFile.setLedgerType("5");      // 安全管理监督检查记录
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        return i;
    }

    @Override
    public AjaxResult exportDetail(Long id) {

        LedgerSafetyManagementInspection inspection = ledgerSafetyManagementInspectionMapper.selectLedgerSafetyManagementInspectionById(id);
        if (inspection == null){
            return AjaxResult.error("当前台账信息不存在");
        }
        // 获取图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(id);
        ledgerFile.setLedgerType("5");      // 安全管理监督检查记录
        ledgerFile.setFileName("1");     // 检查图片
        List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList2(ledgerFile);
        inspection.setImgList(imgList);
        // 复查图片
        ledgerFile.setFileName("2");
        List<Map<String, Object>> checkImgList = ledgerFileMapper.selectLedgerImgList2(ledgerFile);
        inspection.setCheckImgsList(checkImgList);
        if ("0".equals(inspection.getCheckType())){
            inspection.setCheckType("日常检查");
        } else if ("1".equals(inspection.getCheckType())){
            inspection.setCheckType("专项检查");
        }

        SysDictData data = sysDictDataMapper.selectDictDataById(Long.valueOf(inspection.getCheckObject()));
        if (data != null && StringUtils.isNotBlank(data.getDictLabel())){
            inspection.setCheckObject(data.getDictLabel());
        }


        if (inspection.getReinspectionPersonDate() != null){
            inspection.setDate(new SimpleDateFormat("yyyy-MM-dd").format(inspection.getReinspectionPersonDate()));
        }
        String tplPath =this.getClass().getResource("/").getPath() + "excel/安全隐患监督检查记录.xls";
        String fileName = "安全隐患监督检查记录.xls";

        //fileName = FileUtils.setFileDownloadHeader(request, fileName);

        Map<String, Object> beanParams = new HashMap<String, Object>();
        beanParams.put("inspection",inspection);

        XLSTransformer former = new XLSTransformer();
        InputStream in = null;
        OutputStream out = null;
        Workbook workbook = null;
        try {
            in = new BufferedInputStream(new FileInputStream(tplPath));
            workbook = former.transformXLS(in, beanParams);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(fileName));
            if (inspection.getImgList() != null && inspection.getImgList().size() >0){
                int i = 0;
                int k = 0;
                int m = 0;
                for (int j=0;j<inspection.getImgList().size();j++){
                    if (j<2){
                        if (StringUtils.isNotBlank(String.valueOf(inspection.getImgList().get(j).get("url")))){
                            ExportUtil.createPicture(serverConfig.getUrl()+inspection.getImgList().get(j).get("url"),workbook,"Sheet1",(short) (i),6, (short) (i+2), 7);
                        }
                        i=i+2;
                    }else if (j<4){
                        if (StringUtils.isNotBlank(String.valueOf(inspection.getImgList().get(j).get("url")))){
                            ExportUtil.createPicture(serverConfig.getUrl()+inspection.getImgList().get(j).get("url"),workbook,"Sheet1",(short) (k),7, (short) (k+2), 8);
                        }
                        k=k+2;
                    }else {
                        if (StringUtils.isNotBlank(String.valueOf(inspection.getImgList().get(j).get("url")))){
                            ExportUtil.createPicture(serverConfig.getUrl()+inspection.getImgList().get(j).get("url"),workbook,"Sheet1",(short) (m),8, (short) (m+2), 9);
                        }
                        m=m+2;
                    }
                }
            }
            if (inspection.getCheckImgsList() != null && inspection.getCheckImgsList().size() > 0){
                int i = 0;
                int k = 0;
                int m = 0;
                for (int j=0;j<inspection.getCheckImgsList().size();j++){
                    if (j<2){
                        if (StringUtils.isNotBlank(String.valueOf(inspection.getCheckImgsList().get(j).get("url")))){
                            ExportUtil.createPicture(serverConfig.getUrl()+inspection.getCheckImgsList().get(j).get("url"),workbook,"Sheet1",(short) (i),13, (short) (i+2), 14);
                        }
                        i=i+2;
                    }else if (j<4){
                        if (StringUtils.isNotBlank(String.valueOf(inspection.getCheckImgsList().get(j).get("url")))){
                            ExportUtil.createPicture(serverConfig.getUrl()+inspection.getCheckImgsList().get(j).get("url"),workbook,"Sheet1",(short) (k),14, (short) (k+2), 15);
                        }
                        k=k+2;
                    }else {
                        if (StringUtils.isNotBlank(String.valueOf(inspection.getCheckImgsList().get(j).get("url")))){
                            ExportUtil.createPicture(serverConfig.getUrl()+inspection.getCheckImgsList().get(j).get("url"),workbook,"Sheet1",(short) (m),15, (short) (m+2), 16);
                        }
                        m=m+2;
                    }
                }
            }
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null)
            {
                try
                {
                    workbook.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return AjaxResult.error("导出失败");
    }


    @Override
    public int updateDaily(LedgerSafetyManagementInspectionDaily daily){
        int i = dailyMapper.updateLedgerSafetyManagementInspectionDaily(daily);
        if (daily.getCheckImgs() != null && daily.getCheckImgs().length >0){
            for (String path : daily.getCheckImgs()){
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("11");    // 日常检查
                ledgerFile.setLedgerId(daily.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setFileName("2"); // 整改图片
                ledgerFile.setCreateId(daily.getCreateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        // 更改主表中的是否更改
        ledgerSafetyManagementInspectionMapper.updateLedgerSafetyManagementInspection(new LedgerSafetyManagementInspection(daily.getInspectionId(),"","1"));
        // 是否完成整改
        boolean flag = true;
        List<LedgerSafetyManagementInspectionDaily> list = dailyMapper.selectLedgerSafetyManagementInspectionDailyList(new LedgerSafetyManagementInspectionDaily(daily.getInspectionId()));
        List<LedgerSafetyManagementInspectionDaily> collect = list.stream().filter(daily1 -> Objects.equals("1", daily1.getIsProblems())).collect(Collectors.toList());
        if (collect != null && collect.size() >0){
            List<LedgerSafetyManagementInspectionDaily> dailies = collect.stream().filter(daily1 -> Objects.equals("1", daily1.getRectificationType())).collect(Collectors.toList());
            if (dailies != null && dailies.size() >0){
                for (LedgerSafetyManagementInspectionDaily daily1 : dailies){
                    if (!"1".equals(daily1.getIsRectification())){
                        flag = false;
                        break;
                    }
                }
            }
            if (flag) {
                ledgerSafetyManagementInspectionMapper.updateLedgerSafetyManagementInspection(new LedgerSafetyManagementInspection(daily.getInspectionId(),"1"));
            }
        }
        return i;
    }

    @Override
    public List<LedgerSafetyManagementInspectionDaily> selectContentList(Long stationId) {
        return ledgerSafetyManagementInspectionMapper.selectContentList(stationId);
    }
}
